import axios from "axios";
import querystring from "querystring";
import {
  MessageBox,
  Toast
} from "mint-ui";
import {
  JWT_TOKEN
} from "../config/constants";

axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";


axios.defaults.headers['Authorization'] = localStorage.getItem(JWT_TOKEN);

// import baseURL from "../config/config";
// create an axios instance
const service = axios.create({
  baseURL: "", // api的base_url  
  transformRequest: [
    function (data) {
      if (data) {
        data = querystring.stringify(data);
      }
      return data;
    }
  ],
  // withCredentials:true,
  timeout: 100000 // request timeout
});

service.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    // Do something with request error
    return Promise.reject(error);
  }
);

function getUrlParam(name) {  
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");  
  var r = window.location.search.substr(1).match(reg);  
  if (r != null) return unescape(r[2]);  
  return null;
}
let hasLoginCheck = false;

function wxLogin() {
  if (hasLoginCheck) {
    return;
  }
  hasLoginCheck = true;
  var code = getUrlParam("code");
  if (!code) {
    rediret2weixin();
  } else {
    service({
      url: '/api/wx/login',
      method: 'post',
      data: {
        code
      }
    }).then(info => {
      // alert(JSON.stringify(info));
      // console.log(info);
      localStorage.setItem(JWT_TOKEN, info.jwt);
      debugger;
      let returnUrl = localStorage.getItem('returnUrl') || '';
      if (!returnUrl) {
        returnUrl = location.protocol + '//' + location.hostname;
      }
      location.replace(returnUrl);
    });
  }
}

function rediret2weixin() {
  var appId = APPID;
  // var appId = 'wx101f262d4199b623'; //脑洞筹
  let v = location.href;
  v = v.replace(/(&|)code=([^&]+)(&|)/, '');
  localStorage.setItem('returnUrl', v);
  let h = encodeURIComponent(v.split('#')[0]);
  var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + h + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
  window.location.replace(url);
}
// respone interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.errcode !== 0) {
      if (res.errcode == 202) { // 需要登录授权
        return wxLogin();
      } else if (res.errcode == 204) {
        location.hash = '#/register'; //需要注册
        return;
      } else if (res.errcode == 208) {
        // code失效      微信错误
        rediret2weixin();
        return;
      } else if (res.errcode == -1 || (res.errcode >= 300 && res.errcode <= 400)) { // 自定义的错误处理
        return Promise.reject(res);
        // return res;
      }
      //通用错误处理
      Toast({
        message: res.msg,
        position: 'bottom',
        duration: 5000
      });
      // MessageBox({
      //   message: res.msg,
      //   type: "error",
      //   duration: 5 * 1000
      // });
      return Promise.reject(res);
    } else {
      return res.info;
    }
  },
  error => {
    // console.dir(error); // for debug
    if (error.code == "ECONNABORTED") {
      Toast({
        message: "网络异常",
        position: 'bottom'
      });
    }
    return Promise.reject(error);
  }
);

export default service;

export function post(url, data, config) {
  return axios.post(baseURL + url, data, config);
}
